package com.lucky.tjs.config;

import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperConfiguration;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import com.lucky.tjs.entity.ZkConfigProperties;
import com.lucky.tjs.exception.ConfigException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author TJS
 * @Description
 * @create 2023/5/12 6:30
 */
@Configuration
public class ElasticJobRegistryCenterConfig {

    @Resource
    private ZkConfigProperties zkConfigProperties;

    @Bean(initMethod = "init")
    public ZookeeperRegistryCenter regCenter() {
        String serverList = zkConfigProperties.getServerList();
        String namespace = zkConfigProperties.getNamespace();
        if(StringUtils.isBlank(serverList) || StringUtils.isBlank(namespace)){
            throw new ConfigException(" 没有配置serverList 或者是 namespace ");
        }
        ZookeeperConfiguration zookeeperConfiguration = new ZookeeperConfiguration(serverList, namespace);
        zookeeperConfiguration.setBaseSleepTimeMilliseconds(zkConfigProperties.getBaseSleepTimeMilliseconds());
        zookeeperConfiguration.setMaxSleepTimeMilliseconds(zkConfigProperties.getMaxSleepTimeMilliseconds());
        zookeeperConfiguration.setMaxRetries(zkConfigProperties.getMaxRetries());
        zookeeperConfiguration.setSessionTimeoutMilliseconds(zkConfigProperties.getSessionTimeoutMilliseconds());
        zookeeperConfiguration.setConnectionTimeoutMilliseconds(zkConfigProperties.getConnectionTimeoutMilliseconds());
        String digest = zookeeperConfiguration.getDigest();
        if(StringUtils.isNoneBlank(digest)){
            zookeeperConfiguration.setDigest(digest);
        }
        return new ZookeeperRegistryCenter(zookeeperConfiguration);
    }

}

